package com.yociyy.gate.handler;

import com.yociyy.sms.validate.code.ValidateCodeProcessor;
import com.yociyy.sms.validate.code.images.ImageCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import javax.imageio.ImageIO;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 验证码处理器
 * Router Functions是Spring 5新引入的一套Reactive风格（基于Flux和Mono）的函数式接口，
 * 主要包括RouterFunction，HandlerFunction和HandlerFilterFunction，
 * 分别对应Spring MVC中的@RequestMapping，@Controller和HandlerInterceptor（或者Servlet规范中的Filter）。
 * 
 * @author: YoCiyy
 * @date: 2020/5/27
 */
@Slf4j
@Component
public class ValidateCodeHandler  {

	@Autowired
	private Map<String, ValidateCodeProcessor> validateCodeProcessors;

	public Mono<ServerResponse> createCode(ServerRequest serverRequest) {
		Map<String, Object> params = new HashMap<>();
		String randomStr = UUID.randomUUID().toString().replaceAll("-", "");
		params.put("randomStr", randomStr);
		FastByteArrayOutputStream os = new FastByteArrayOutputStream();
		try {
			ImageCode imageCode = (ImageCode) validateCodeProcessors.get("imageCodeProcessor").create(params);
			ImageIO.write(imageCode.getImage(), "JPEG", os);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ServerResponse.status(HttpStatus.OK).contentType(MediaType.IMAGE_JPEG).header("randomstr", randomStr)
				.body(BodyInserters.fromResource(new ByteArrayResource(os.toByteArray())));
	}
}
